package cn.com.wdjedu.androidapp.wjeduandroid.ui.videoshow;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.superplayer.library.SuperPlayer;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.wdjedu.androidapp.wjeduandroid.R;
import cn.com.wdjedu.androidapp.wjeduandroid.mvp.video.videoBean;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.Constanct;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.global.GlobalContext;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.utils.CommonUtils;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.utils.VideoShowFragmentFactory;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.TabPageIndicator;
import cn.com.wdjedu.androidapp.wjeduandroid.ui.baseui.AbstractAppActivity;
import cn.com.wdjedu.androidapp.wjeduandroid.ui.videoshow.fragment.ChapterFragment;

/**
 * 视频展示 横屏
 */

@SuppressWarnings("FieldCanBeLocal")
public class VideoShowActivity extends AbstractAppActivity implements SuperPlayer.OnNetChangeListener {
    //常量当前时间
    public static final String CURRENT_TIME = "current_time";

    //导航栏对象
    TabPageIndicator mIndicator;
    //ViewPager承载
    ViewPager mViewPager;


    @BindView(R.id.view_super_player)
    SuperPlayer mViewSuperPlayer;
    @BindView(R.id.tv_super_player_complete)
    TextView mTvSuperPlayerComplete;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    //记录当前播放的时长
    private int currentTime;

    //播放器播放的url
    private String url;
    //是否橫屏
    private boolean isLand;

    //初始化章节显示
    private BasePagerAdapter adapter;
    private ChapterFragment fragment;
    private int PlayingID;

    public int position = 0;

    public int getPosition() {
        return position;
    }
    public void setPosition(int position) {
        this.position = position;
    }

    //常量播放位置
    public static final String PLAYING_POSITION = "playing_position";

    public static Intent newIntent() {
        Intent intent = new Intent(GlobalContext.getInstance().getApplicationContext(), VideoShowActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        return intent;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_show);

        ButterKnife.bind(this);
        initView();
        initData(savedInstanceState);
        initTagAdapter();
    }

    private void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            currentTime = savedInstanceState.getInt(CURRENT_TIME);
            setPosition(savedInstanceState.getInt(PLAYING_POSITION));
        }
    }

    /**
     * 初始化导航栏
     */
    private void initTagAdapter() {
//        if (!isLand){
        adapter = new BasePagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(adapter);
        mIndicator.setViewPager(mViewPager);
        setTabPagerIndicator();
//        }
        playVideo(); /*视屏播放*/

    }

    private void initView() {
        mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        //如果为空就是横屏 如果为空就是竖屏
        if (mIndicator != null) {
            isLand = false;
        } else {
            isLand = true;
        }
        //this.setPosition(0);

        //通过判断当前播放的视频id，来决定显示哪些章节，ChapterFragment中回调
        Bundle bundle = this.getIntent().getExtras();
        PlayingID = bundle.getInt("id");
    }


    /**
     * 视屏播放
     */
    public void playVideo() {
        //url = "http://baobab.wandoujia.com/api/v1/playUrl?vid=2614&editionType=normal";
        //url = "http://flv2.bn.netease.com/videolib3/1701/24/eXOLU3162/HD/eXOLU3162-mobile.mp4";
        //url = "http://47.90.92.155/edu/public/uploads/video/java.mov";

        // url= Constanct.VIDEO_URL+videosBean.getVideo_path();
        // Constanct.PLAYING_URL =videosBean.getVideo_path();
        //http://olm3zb2gw.bkt.clouddn.com/java-1-1-1.mp4

        // Toast.makeText(getApplication()," VideoShowActivity内的PlayVideo()被调用"+videopath,Toast.LENGTH_LONG).show();
        mViewSuperPlayer.setNetChangeListener(true)//设置监听手机网络的变化
                .setOnNetChangeListener(this)//实现网络变化的回调
                .onPrepared(new SuperPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared() {
                        /**
                         * 监听视频是否已经准备完成开始播放。（可以在这里处理视频封面的显示跟隐藏）
                         */
                    }
                }).onComplete(new Runnable() {
            @Override
            public void run() {
                /**
                 * 监听视频是否已经播放完成了。（可以在这里处理视频播放完成进行的操作）
                 */
                setPosition(getPosition() + 1);
                //获取到下一个播放的url
                 fragment = (ChapterFragment) getSupportFragmentManager().findFragmentByTag(
                        "android:switcher:" + R.id.viewPager + ":0");
                if (fragment != null)  // could be null if not instantiated yet
                {
                    if (fragment.getView() != null) {
                        //no need to call if fragment's onDestroyView()
                        //has since been called.
                        //Toast.makeText(getApplication(),"接收的listBean大小为："+fragment.getListsPast().size(),Toast.LENGTH_LONG).show();
                        List<videoBean.DataBean.ListsBean> bean=fragment.getListsPast();
                        if(getPosition() < bean.size()) {
                            if (bean.size() != 0 && bean != null && bean.get(position) != null) {
                                String nextUrl = bean.get(position).getVideo_path();
                                Constanct.PLAYING_URL = nextUrl;
                                Constanct.PLAYING_NAME = bean.get(position).getName();
                                playVideo();
                                currentTime = 0;
                                // 获取adpater刷新
                                if (fragment.getChapterAdapter() != null) {
                                    fragment.getChapterAdapter().notifyDataSetChanged();
                                }
                            }
                        }else{
                            Toast.makeText(getApplication(),"恭喜你，本单元已学习完成！",Toast.LENGTH_LONG).show();
                        }

                    }
                }

            }
        }).onInfo(new SuperPlayer.OnInfoListener() {
            @Override
            public void onInfo(int what, int extra) {
                /**
                 * 监听视频的相关信息。
                 */

            }
        }).onError(new SuperPlayer.OnErrorListener() {
            @Override
            public void onError(int what, int extra) {
                /**
                 * 监听视频播放失败的回调
                 */

            }
        }).setTitle(Constanct.PLAYING_NAME)//设置视频的titleName
                .playSwitch(Constanct.VIDEO_URL + Constanct.PLAYING_URL);//开始播放视频
        mViewSuperPlayer.setScaleType(SuperPlayer.SCALETYPE_FITXY);
        mViewSuperPlayer.setPlayerWH(0, mViewSuperPlayer.getMeasuredHeight());//设置竖屏的时候屏幕的高度，如果不设置会切换后按照16:9的高度重置
        if (currentTime > 0) {
            mViewSuperPlayer.play(Constanct.VIDEO_URL + Constanct.PLAYING_URL, currentTime);
        }

    }

    /**
     * 获取视屏当前播放时间点
     */
    private int getVideoPosition() {
        return mViewSuperPlayer.getCurrentPosition();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //保存当前时间
        outState.putInt(CURRENT_TIME, currentTime);
        outState.putInt(PLAYING_POSITION,getPosition());
    }

    public int getPlayId() {
        return PlayingID;
    }

    /**
     * 网络链接监听类
     */
    @Override
    public void onWifi() {
        Toast.makeText(this, "当前网络环境是WIFI", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onMobile() {
        Toast.makeText(this, "当前网络环境是手机网络", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDisConnect() {
        Toast.makeText(this, "网络链接断开", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNoAvailable() {
        Toast.makeText(this, "无网络链接", Toast.LENGTH_SHORT).show();
    }


    /**
     * 下面的这几个Activity的生命状态很重要
     */
    @Override
    public void onPause() {
        super.onPause();
        if (mViewSuperPlayer != null) {
            currentTime = mViewSuperPlayer.getCurrentPosition();
            mViewSuperPlayer.onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mViewSuperPlayer != null) {
            mViewSuperPlayer.onResume();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mViewSuperPlayer != null) {  /*播放器释放*/
            mViewSuperPlayer.onDestroy();
        }
    }

    @Override
    public void onDestroy() {

        if (mViewSuperPlayer != null) {  /*播放器释放*/
            mViewSuperPlayer.onDestroy();
        }
        super.onDestroy();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mViewSuperPlayer != null) {
            mViewSuperPlayer.onConfigurationChanged(newConfig);
        }
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mIndicator.setVisibility(View.GONE);
            mViewPager.setVisibility(View.GONE);
            setPosition(position);
        } else {
            mIndicator.setVisibility(View.VISIBLE);
            mViewPager.setVisibility(View.VISIBLE);
            fragment = (ChapterFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":0");
            // 获取adpater刷新
            if (fragment.getChapterAdapter()!=null){
                //Toast.makeText(getApplication(),"测试位置！！！！！！！！！！！"+getPosition(),Toast.LENGTH_LONG).show();
                fragment.getChapterAdapter().notifyDataSetChanged();
            }

        }
//        initTagAdapter();
    }

    /**
     * 设置导航栏的参数类型
     */
    private void setTabPagerIndicator() {
        //#50b2f5蓝色
        //
        mIndicator.setIndicatorMode(TabPageIndicator.IndicatorMode.MODE_NOWEIGHT_EXPAND_NOSAME);// 设置模式，一定要先设置模式
        mIndicator.setDividerColor(Color.parseColor("#00000000"));// 设置分割线的颜色
        mIndicator.setDividerPadding(CommonUtils.dip2px(GlobalContext.getInstance(), 10));
        mIndicator.setIndicatorColor(Color.parseColor("#50b2f5"));// 设置底部导航线的颜色
        mIndicator.setTextColorSelected(Color.parseColor("#50b2f5"));// 设置tab标题选中的颜色
        mIndicator.setTextColor(Color.parseColor("#797979"));// 设置tab标题未被选中的颜色
        mIndicator.setTextSize(CommonUtils.sp2px(GlobalContext.getInstance(), 14));// 设置字体大小
    }


    /**
     * 底部展示的四个模块的Fragmnet适配器
     */
    class BasePagerAdapter extends FragmentPagerAdapter {
        String[] titles;

        public BasePagerAdapter(FragmentManager fm) {
            super(fm);
            this.titles = CommonUtils.getStringArray(R.array.expand_titles);
        }

        @Override
        public Fragment getItem(int position) {
            return VideoShowFragmentFactory.createForNoExpand(position);
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }


}
